<?php

namespace common\models\c2\entity;

use common\helpers\CodeGenerator;
use kzo\base\models\statics\EntityModelStatus;
use kzo\user\models\BeUser;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%inventory_delivery_note}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $code
 * @property string $label
 * @property string $warehouse_id
 * @property string $sales_order_id
 * @property string $customer_id
 * @property string $occurrence_date
 * @property string $grand_total
 * @property string $contact_man
 * @property string $cs_name
 * @property string $sender_name
 * @property string $financial_name
 * @property string $payment_method
 * @property string $delivery_method
 * @property string $memo
 * @property string $remote_ip
 * @property string $updated_by
 * @property string $created_by
 * @property integer $state
 * @property integer $status
 * @property integer $position
 * @property string $updated_at
 * @property string $created_at
 */
class InventoryDeliveryNote extends \kzo\base\models\ActiveRecord
{

    public $items;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%inventory_delivery_note}}';
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            BlameableBehavior::className()
        ]); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'warehouse_id', 'sales_order_id', 'customer_id', 'updated_by', 'created_by', 'state', 'status', 'position'], 'integer'],
            [['code'], 'required'],
            [['occurrence_date', 'updated_at', 'created_at', 'items'], 'safe'],
            [['grand_total'], 'number'],
            [['memo'], 'string'],
            [['code', 'label', 'contact_man', 'cs_name', 'sender_name', 'financial_name', 'payment_method', 'delivery_method', 'remote_ip'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'code' => Yii::t('app.c2', 'Code'),
            'label' => Yii::t('app.c2', 'Label'),
            'warehouse_id' => Yii::t('app.c2', 'Warehouse ID'),
            'sales_order_id' => Yii::t('app.c2', 'Sales Order ID'),
            'customer_id' => Yii::t('app.c2', 'Customer ID'),
            'occurrence_date' => Yii::t('app.c2', 'Occurrence Date'),
            'grand_total' => Yii::t('app.c2', 'Grand Total'),
            'contact_man' => Yii::t('app.c2', 'Contact Man'),
            'cs_name' => Yii::t('app.c2', 'Cs Name'),
            'sender_name' => Yii::t('app.c2', 'Sender Name'),
            'financial_name' => Yii::t('app.c2', 'Financial Name'),
            'payment_method' => Yii::t('app.c2', 'Payment Method'),
            'delivery_method' => Yii::t('app.c2', 'Delivery Method'),
            'memo' => Yii::t('app.c2', 'Memo'),
            'remote_ip' => Yii::t('app.c2', 'Remote Ip'),
            'updated_by' => Yii::t('app.c2', 'Updated By'),
            'created_by' => Yii::t('app.c2', 'Created By'),
            'state' => Yii::t('app.c2', 'State'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
            'created_at' => Yii::t('app.c2', 'Created At'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\InventoryDeliveryNoteQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\InventoryDeliveryNoteQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
        if ($this->isNewRecord) {
            $this->code = CodeGenerator::getCodeByDate($this, 'DN');
        }
    }

    public function getCreator()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'created_by']);
    }

    public function getUpdater()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'updated_by']);
    }

    public function getCustomer()
    {
        return $this->hasOne(FeUser::className(), ['id' => 'customer_id']);
    }

    public function getWarehouse()
    {
        return $this->hasOne(Warehouse::className(), ['id' => 'warehouse_id']);
    }

    public function getNoteItems()
    {
        return $this->hasMany(InventoryDeliveryNoteItem::className(), ['note_id' => 'id']);
    }

    public function loadItems()
    {
        $this->items = $this->getNoteItems()->all();
    }

    public function getSalesOrder()
    {
        return $this->hasOne(SalesOrder::className(), ['id' => 'sales_order_id']);
    }

    public function beforeDelete()
    {
        foreach ($this->getNoteItems()->all() as $item) {
            $item->delete();
        }
        return parent::beforeDelete(); // TODO: Change the autogenerated stub
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if ($insert) {
            $this->linkSalesOrder();
        } else {
            if (isset($changedAttributes['sales_order_id'])) {
                foreach ($this->getNoteItems()->all() as $item) {
                    $item->delete();
                }
                $this->linkSalesOrder();
                return;
            }
            $this->changeNoteItems();
        }
    }

    public function linkSalesOrder()
    {
        $items = $this->salesOrder->orderItems;
        foreach ($items as $item) {
            /** @var $item SalesOrderItem */
            $need_send = $item->pieces - $item->send_pieces;
            if ($need_send > 0) {
                $attributes = [
                    'note_id' => $this->id,
                    'customer_id' => $this->customer_id,
                    'product_id' => $item->product_id,
                    'product_label' => $item->product_label,
                    'product_sku_id' => $item->product_sku_id,
                    'sku_label' => $item->sku_label,
                    'package_id' => $item->package_id,
                    'package_label' => $item->package_label,
                    'measure_id' => $item->measure_id,
                    'pieces' => $item->pieces,
                    'quantity' => $item->quantity,
                    'price' => $item->price,
                    'subtotal' => $item->subtotal,
                    'position' => isset($item['position']) ? $item['position'] : 0,
                    'status' => EntityModelStatus::STATUS_INACTIVE
                ];
                $itemModel = new InventoryDeliveryNoteItem();
                $itemModel->setAttributes($attributes);
                $itemModel->link('owner', $this);
            }
        }
        $this->updateAttributes(['grand_total' => $this->salesOrder->grand_total]);
    }

    public function changeNoteItems()
    {

        $grand_total = 0.000;
        foreach ($this->items as $item) {
            $pieces = isset($item['pieces']) ? $item['pieces'] : 0;
            $price = isset($item['price']) ? $item['price'] : 0;
            $attributes = [
                'product_id' => isset($item['product_id']) ? $item['product_id'] : 0,
                'product_sku_id' => isset($item['product_sku_id']) ? $item['product_sku_id'] : 0,
                'package_id' => isset($item['package_id']) ? $item['package_id'] : 0,
                'measure_id' => isset($item['measure_id']) ? $item['measure_id'] : 0,
                'pieces' => $pieces,
                'price' => $price,
                'quantity' => 0,
                // 'send_pieces' => 0,
                'subtotal' => 0,
                'memo' => isset($item['memo']) ? $item['memo'] : '',
                'position' => isset($item['position']) ? $item['position'] : 0,
                'status' => EntityModelStatus::STATUS_INACTIVE
            ];

            if (($model = Product::findOne($item['product_id'])) != null) {
                $attributes['product_label'] = $model->label;
            }

            if (($model = ProductSku::findOne($item['product_id'])) != null) {
                $attributes['sku_label'] = $model->label;
            }

            if (($model = ProductPackage::findOne($item['product_id'])) != null) {
                $attributes['package_label'] = $model->label;
            }

            $package = ProductPackage::findOne($item['package_id']);
            if (!is_null($package)) {
                $attributes['quantity'] = $package->capacity * $pieces;
                $attributes['subtotal'] = $price * $attributes['quantity'];
                $grand_total += $attributes['subtotal'];
            }

            if (isset($item['id']) && $item['id'] == '') {
                $itemModel = new InventoryDeliveryNoteItem();
                $itemModel->setAttributes($attributes);
                $itemModel->link('owner', $this);
            } else {
                $itemModel = InventoryDeliveryNoteItem::findOne($item['id']);
                if (!is_null($itemModel)) {
                    $itemModel->updateAttributes($attributes);
                }
            }
        }
        $this->updateAttributes(['grand_total' => $grand_total]);
    }

}
